package top.hkyzf.study.leetcode.array;

import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description: 
 * @author zhufeng
 * @date 2024/1/25 0025 15:45
 * @version V1.0
 */
public class 计算K置位下标对应元素的和_2859 {
    public int sumIndicesWithKSetBits(List<Integer> nums, int k) {
        int sum = 0;
        for (int i = 0; i < nums.size(); i++) {
            int s = calcBit2(i);
            if (s == k) {
                sum += nums.get(i);
            }
        }
        return sum;
    }

    private int calcBit(int i) {
        int rtn = 0;
        while (i != 0) {
            rtn += i % 2;
            i = i / 2;
        }
        return rtn;
    }

    private int calcBit2(int i) {
        int rtn = 0;
        while (i != 0) {
            // 去掉最右侧的一个 1
            i = i & (i-1);
            rtn++;
        }
        return rtn;
    }

    @Test
    public void testSum () {
        List<Integer> nums = Arrays.asList(4,3,2,1);
        int k = 2;
        System.out.println(sumIndicesWithKSetBits(nums, k));
    }
}
